<?php
declare(strict_types=1);
namespace Aincrid\MySwoole\Storage;

use Aincrid\MySwoole\Config;
use Aincrid\MySwoole\Facade\Container;

class LocalDriver implements iDriver
{
    protected array $configs = [];


    public function __construct()
    {
        $this->configs = Container::get(Config::class)->get('filesystem.disks.local');
    }

    /**
     * @param string $path
     * @return bool
     */
    public function exists(string $path): bool
    {
        return is_dir($path) || file_exists($path);
    }

    /**
     *
     * @param string $dir
     * @return bool
     */
    public function makeDirectory(string $dir): bool
    {
        if (is_dir($dir)) {
            return true;
        }
        return mkdir($dir, 0777, true);
    }

    /**
     *
     * @param string $fileName
     * @param mixed $content
     * @return bool
     */
    public function put(string $fileName, $content): bool|int
    {
        return \Swoole\Coroutine\System::writeFile($fileName, $content, FILE_APPEND);
    }

    /**
     *
     * @param string $dir
     * @return bool
     */
    public function deleteDir(string $dir): bool
    {
        if (is_dir($dir)) {
            $dirResource = opendir($dir);
            while ($dirName = readdir($dirResource)) {
                if ($dirName != '.' && $dirName != '..') {
                    if (is_file($dir . '/' . $dirName)) {
                        $this->deleteFile($dir . '/' . $dirName);
                    } else {
                        $this->deleteDir($dir . '/' . $dirName);
                    }
                }
            }
            closedir($dirResource);
            return rmdir($dir);
        } else {
            return $this->deleteFile($dir);
        }
    }

    public function deleteFile(string $filename): bool
    {
        return unlink($filename);
    }
}